package com.mo.lib.view.recyclerview

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import android.widget.ScrollView
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dylanc.longan.dp
import com.google.android.flexbox.*

/**
 * @ author：mo
 * @ data：2022/3/26:11:01
 * @ 功能：
 */
open class KRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : RecyclerView(context, attrs, defStyle) {
    /** 是否滚动，为了处理当scrrolview嵌套recyclerview的时候数据显示不全 */
    private var scroolSta = true
    private var mMaxHeight = -1
    private var mInterceptTouch = false
    private var onPageChangeListener: RvPageChangeHelper.OnPageChangeListener? = null
    private var rvPageChangeHelper: RvPageChangeHelper? = null

    init {
        layoutV()
    }

    fun setMaxHeight(height: Int) = apply {
        mMaxHeight = height.dp.toInt()
        invalidate()
    }

    fun setInterceptTouch(isInterceptTouch: Boolean) = apply {
        mInterceptTouch = isInterceptTouch
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (!scroolSta) { //        设置不滚动
            val expandSpec = MeasureSpec.makeMeasureSpec(Int.MAX_VALUE shr 2, MeasureSpec.AT_MOST)
            super.onMeasure(widthMeasureSpec, expandSpec)
        } else {
            val hSize = MeasureSpec.getSize(heightMeasureSpec)
            var heightSpec = 0
            heightSpec = if (mMaxHeight < 0) {
                heightMeasureSpec
            } else {
                when (MeasureSpec.getMode(heightMeasureSpec)) {
                    MeasureSpec.AT_MOST -> MeasureSpec.makeMeasureSpec(Math.min(hSize, mMaxHeight), MeasureSpec.AT_MOST)
                    MeasureSpec.UNSPECIFIED -> MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST)
                    MeasureSpec.EXACTLY -> MeasureSpec.makeMeasureSpec(Math.min(hSize, mMaxHeight), MeasureSpec.EXACTLY)
                    else -> MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST)
                }
            }
            super.onMeasure(widthMeasureSpec, heightSpec)
        }
    }

    /** 获取当前列表所用的布局管理器*/
    override fun getLayoutManager(): LayoutManager? {
        return super.getLayoutManager()
    }

    /** 获取recycleview当前显示部分的高度*/
    fun getDisplayHight(): Int {
        return computeVerticalScrollExtent()
    }

    /** 个方法用来判断 水平方向的滑动*/
    override fun canScrollHorizontally(direction: Int): Boolean {
        return super.canScrollHorizontally(direction)
    }

    /**
     * 判断View在竖直方向是否还能向上，向下滑动。
     * 可判断是否到顶或触底
     * RecyclerView.canScrollVertically(1)的值表示是否能向下滚动，false表示已经滚动到底部
     * RecyclerView.canScrollVertically(-1)的值表示是否能向上滚动，false表示已经滚动到顶部
     *
     * @param direction -1 表示手指向下滑动（屏幕向上滑动）， 1 表示手指向上滑动（屏幕向下滑动）。
     * @return
     */
    override fun canScrollVertically(direction: Int): Boolean {
        return super.canScrollVertically(direction)
    }

    open fun setViewPageType(type: Int, helper: RvPageChangeHelper.OnPageChangeListener?) {
        this.layoutH()
        val snapHelper: SnapHelper = if (type == 0) {
            LinearSnapHelper()
        } else {
            PagerSnapHelper()
        }
        snapHelper.attachToRecyclerView(this)
        helper?.let {
            this.onPageChangeListener=helper
            addOnScrollListener(RvPageChangeHelper(snapHelper, it).also { rvPageChangeHelper = it })
        }
    }

    override fun scrollToPosition(position: Int) {
        super.scrollToPosition(position)
        onPageChangeListener?.let {
            rvPageChangeHelper!!.setOldPosition()
            it.onPageSelected(position)
        }
    } //    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
    //            super.onInterceptTouchEvent(ev)
    //            parent.requestDisallowInterceptTouchEvent(true)
    //            return true
    //        }
}

/** 设置垂直布局管理*/
fun RecyclerView.layoutV(): RecyclerView {
    return this.apply {
        val linearLayoutManager: LinearLayoutManager = object : LinearLayoutManager(context) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        if (this.parent is ScrollView || this.parent is NestedScrollView) { //解决数据加载不完的问题
            this.isNestedScrollingEnabled = false
            setHasFixedSize(true) //解决数据加载完成后, 没有停留在顶部的问题
            this.isFocusable = false
        }

        this.layoutManager = linearLayoutManager //跟scrollview兼容
    }
}

/** 设置水平布局管理*/
fun RecyclerView.layoutH(): RecyclerView {
    return this.apply {
        val linearLayoutManager: LinearLayoutManager = object : LinearLayoutManager(context) {
            override fun canScrollHorizontally(): Boolean {
                return true
            }
        }
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        this.layoutManager = linearLayoutManager
    }
}

/** 设置表格布局管理*/
fun RecyclerView.layoutG(spanCount: Int): RecyclerView {
    return this.apply {
        val gridLayoutManager = GridLayoutManager(context, spanCount)
        this.layoutManager = gridLayoutManager //设置间距
        //设置间距
        this.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.left = 6
                outRect.bottom = 6 //由于每行都只有3个，所以第一个都是3的倍数，把左边距设为0
                if (parent.getChildLayoutPosition(view) % spanCount == 0) {
                    outRect.left = 0
                }
            }
        })
    }
}

/** 设置瀑布布局管理*/
fun RecyclerView.layoutSG(spanCount: Int): RecyclerView {
    return this.apply {
        val staggeredGridLayoutManager = StaggeredGridLayoutManager(spanCount, LinearLayoutManager.VERTICAL)
        this.layoutManager = staggeredGridLayoutManager
    }
}

/** 设置自适应换行布局管理*/
fun RecyclerView.layoutTagFlow(divider: Int): RecyclerView {
    return this.apply {
        val manager = object : FlexboxLayoutManager(context, FlexDirection.ROW, FlexWrap.WRAP) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        manager.flexWrap = FlexWrap.WRAP;
        manager.flexDirection = FlexDirection.ROW;
        manager.alignItems = AlignItems.CENTER;
        manager.justifyContent = JustifyContent.FLEX_START;
        this.layoutManager = manager
    }
}

fun <T> RecyclerView.setAdapterQuick(layoutId: Int, data: MutableList<T>, block: (BaseViewHolder, T) -> Unit): RecyclerView {
    return this.apply {
        this.adapter = object : BaseQuickAdapter<T, BaseViewHolder>(layoutId, data) {
            override fun convert(holder: BaseViewHolder, item: T) {
                block.invoke(holder, item)
            }
        }
    }
}

fun <T> getAdapterQuick(layoutId: Int, data: MutableList<T>, block: (BaseViewHolder, T) -> Unit): BaseQuickAdapter<T, BaseViewHolder> {
    return object : BaseQuickAdapter<T, BaseViewHolder>(layoutId, data) {
        override fun convert(holder: BaseViewHolder, item: T) {
            block.invoke(holder, item)
        }
    }
}

/** 设置某一项置顶*/
fun RecyclerView.setItemToTop(position: Int) {
    layoutManager?.let {
        when (it) {
            is LinearLayoutManager -> {
                it.scrollToPositionWithOffset(position, 0)
            }
            is GridLayoutManager -> {
                it.scrollToPositionWithOffset(it.spanCount / position, 0)
            }
            is StaggeredGridLayoutManager -> {
                it.scrollToPositionWithOffset(it.spanCount / position, 0)
            }
        }
    }

}
/** 直接置顶*/
fun RecyclerView.goToPosition(position: Int) {
    if (position>=0){
        when (this.layoutManager) {
            is LinearLayoutManager -> {
                (this.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(position, 0)
            }
        }
    }

}
/** 平滑的滚到置顶*/
fun RecyclerView.goToPosition2(position: Int) {
    if (position>=0){
        val smoothScroller: LinearSmoothScroller = object : LinearSmoothScroller(context) {
            override fun getHorizontalSnapPreference(): Int {
                return SNAP_TO_START
            }

            override fun getVerticalSnapPreference(): Int {
                return SNAP_TO_START
            }
        }
        smoothScroller.targetPosition = position
        this.layoutManager?.startSmoothScroll(smoothScroller)
    }
}